import router from "."

import modal from "@/plugins/modal"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import store from "@/store/index.js"

NProgress.configure({showSpinner: false})

const whiteList = ["/login", "/auth-redirect", "/bind", "/register", "/test"]

router.beforeEach((to, from, next) => {
    NProgress.start()

    if (store.user.getToken()) {
        to.meta.title && store.settings.setTitle(to.meta.title)
        /* has token*/
        if (to.path === "/login") {
            next({path: "/index"})
            NProgress.done()
        } else {
            if (store.user.roles.length === 0) {
                // 判断当前用户是否已拉取完user_info信息
                store.user.getInfo().then(() => {
                    // 请求用户信息中角色还为空，不能登录
                    if (store.user.roles.length === 0){
                        store.user.logOut().then(() => {
                            modal.msgError("该账号未绑定角色，不能登录！")
                            next({path: "/"})
                        }).catch((err) => {
                            next({path: "/"})
                        })
                        NProgress.done()
                    }else{
                        store.permission.generateRoutes().then((accessRoutes) => {
                            // 根据roles权限生成可访问的路由表
                            accessRoutes.forEach((res) => {
                                // 给name添加path，解决命名冲突问题
                                if (res.children) res.children.forEach(child => child.name = res.path + child.path)
                                router.addRoute(res)
                            })
                            next({...to, replace: true}) // hack方法 确保addRoutes已完成
                        })
                    }
                }).catch((err) => {
                    console.log("退出登录")
                    store.user.logOut().then(() => {
                        modal.msgError(err)
                        next({path: "/"})
                    }).catch((err) => {
                        next({path: "/"})
                    })
                })
            } else {
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${ to.fullPath }`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
